//
//  NetWorkTool.m
//  AAIM
//
//  Created by awh on 2019/11/22.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "NetWorkTool.h"
#import "NSDictionary+Merge.h"
#import "NSArray+String.h"
#import "NSDictionary+URL.h"
#import "NSDictionary+Merge.h"
//#import "SWLogger.h"
#import "NSString+MD5.h"
#import "ChatTool.h"
#import "RSA.h"
#import "NSString+AES.h"
#import "NSString+DictionaryValue.h"
#import "IMClient.h"
#import <CloudPushSDK/CloudPushSDK.h>

@interface NetWorkTool ()

@property (nonatomic, strong) AFHTTPSessionManager * manager;
@property (nonatomic, strong) AFHTTPSessionManager * chatFileManager;
@property (nonatomic, strong) AFHTTPSessionManager * upLoadManager;
@property (nonatomic,strong) AFHTTPSessionManager * publicManager;

@property (nonatomic, strong) AFHTTPSessionManager * downloadManager;

@property (nonatomic, strong) NSMutableDictionary *dispatchTable;

@property (nonatomic, assign) BOOL isConnect;

@end
@implementation NetWorkTool

#pragma mark - 内部方法

- (NSMutableDictionary *)dispatchTable
{
    if (_dispatchTable == nil) {
        _dispatchTable = [[NSMutableDictionary alloc] init];
    }
    return _dispatchTable;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        // 普通请求
        self.manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:MainURl]];
        //设置请求类型
        self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        self.manager.requestSerializer.timeoutInterval = 100;
        //设置响应类型
        self.manager.responseSerializer = [AFJSONResponseSerializer serializer];//
        self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", @"text/json", @"text/javascript",@"text/plain",@"image/gif",nil];
        NSString *deviceUUID = [[UIDevice currentDevice].identifierForVendor UUIDString];//uuid
        [self.manager.requestSerializer setValue:deviceUUID forHTTPHeaderField:@"uuid"];
        [self.manager.requestSerializer setValue:[LoginManager shareLoginManager].userModel.token forHTTPHeaderField:@"t"];
        [self.manager.requestSerializer setValue:@"011001000001" forHTTPHeaderField:@"h"];
        [self.manager.requestSerializer setValue:@"www.liftIM.con" forHTTPHeaderField:@"k"];
        [self.manager.requestSerializer setValue:[CloudPushSDK getDeviceId] forHTTPHeaderField:@"uuid"];
        [self.manager.requestSerializer setValue:[CloudPushSDK getDeviceId] forHTTPHeaderField:@"udid"];
        
       //公众号接口
        self.publicManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:PublicURl]];
        //设置请求类型
        self.publicManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        self.publicManager.requestSerializer.timeoutInterval = 100;
        //设置响应类型
        self.publicManager.responseSerializer = [AFJSONResponseSerializer serializer];//
        self.publicManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", @"text/json", @"text/javascript",@"text/plain",@"image/gif",nil];
        [self.publicManager.requestSerializer setValue:deviceUUID forHTTPHeaderField:@"uuid"];
        [self.publicManager.requestSerializer setValue:[LoginManager shareLoginManager].userModel.token forHTTPHeaderField:@"t"];
        [self.publicManager.requestSerializer setValue:@"011001000001" forHTTPHeaderField:@"h"];
        [self.publicManager.requestSerializer setValue:@"www.liftIM.con" forHTTPHeaderField:@"k"];
        [self.publicManager.requestSerializer setValue:[CloudPushSDK getDeviceId] forHTTPHeaderField:@"uuid"];
        [self.publicManager.requestSerializer setValue:[CloudPushSDK getDeviceId] forHTTPHeaderField:@"udid"];
        
        // 聊天文件上传下载
        self.chatFileManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:HeaderImageFileURL]];
        //设置请求类型
        self.chatFileManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        //设置响应类型
        self.chatFileManager.responseSerializer = [AFJSONResponseSerializer serializer];
        self.chatFileManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", @"text/json", @"text/javascript",@"text/plain",@"image/gif",nil];
        
        
        // 聊天语音
        self.downloadManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:LIFT_APP_USER_VOICE_KEY]];
//        self.downloadManager =[[AFHTTPSessionManager alloc]init];
        self.downloadManager.requestSerializer.timeoutInterval = 100;
        //设置请求类型
        self.downloadManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        //设置响应类型
        self.downloadManager.responseSerializer = [AFJSONResponseSerializer serializer];
        self.downloadManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", @"text/json", @"text/javascript",@"text/plain",@"image/gif",nil];
        
        
        // 图片文件上传
        self.upLoadManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:HeaderImageFileURL]];
        //设置请求类型
        self.upLoadManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        //设置响应类型
        self.upLoadManager.responseSerializer = [AFJSONResponseSerializer serializer];
        self.upLoadManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", @"text/json", @"text/javascript",@"text/plain",@"image/gif",@"image/png",@"image/jpg",@"image/jpeg",@"multipart/form-data",@"*/*",nil];

        
    }
    return self;
}


+ (instancetype)shareInstance {
    
    static NetWorkTool * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

//用于请求app版本
- (void)requestAppVersionWithPath:(NSString *)url method:(HttpRequestType)method paramenters:(NSMutableDictionary *)params completion:(SuccessBlock)completion
{
    [self requestWithManager:self.manager path:url method:method paramenters:params  httpBody:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        completion(task,responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error, id responseObject) {
        completion(task,responseObject);
    }];
}

//请求配置信息
- (void)getAppInfoPath:(NSString *)url method:(HttpRequestType)method completion:(SuccessBlock)completion{
    [self requestWithManager:self.manager path:url method:method paramenters:nil httpBody:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        completion(task,responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error, id responseObject) {
        completion(task,responseObject);
    }];
}

//公众号
- (void)requestPublicWithPath:(NSString *)url method:(HttpRequestType)method paramenters:(NSMutableDictionary *)params completion:(ResultResponseBlock)completion
{
     [self requestWithManager:self.publicManager path:url method:method paramenters:params completion:completion];
}
- (void)requestWithPath:(NSString *)url method:(HttpRequestType)method paramenters:(NSMutableDictionary *)params completion:(ResultResponseBlock)completion
{
    [self requestWithManager:self.manager path:url method:method paramenters:params completion:completion];
}

- (void)requestWithManager:(AFHTTPSessionManager *)manager
                      path:(NSString *)url
                    method:(HttpRequestType)method
               paramenters:(NSMutableDictionary *)params completion:(ResultResponseBlock)completion
{
    /*接口加token*/
    //    [params setValue:[CacheTool readUserDefaults:@"user_token"] forKey:@"token"];
    
    
    [self requestWithManager:manager path:url method:method paramenters:params  httpBody:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        SLResultModel *model = [SLResultModel mj_objectWithKeyValues:responseObject];
        model.rawdata = responseObject;
        
        completion(model);
        //token失效
        if ([responseObject[@"code"] integerValue]==3) {
            NSLog(@"token失效");
            //            [[IMClient sharedClient]closeConnect];
            //            [[LoginManager shareLoginManager] loginOut];
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error, id responseObject) {
        SLResultModel *model = [SLResultModel mj_objectWithKeyValues:responseObject];
        model.rawdata = responseObject;
        model.msg = @"网络请求失败了";
        completion(model);
    }];
}

- (void)requestWithManager:(AFHTTPSessionManager *)manager
                      path:(NSString *)url
                    method:(HttpRequestType)method
                  httpBody:(NSData *)httpBody
                completion:(ResultResponseBlock)completion
{
    [self requestWithManager:manager path:url method:method paramenters:nil httpBody:httpBody success:^(NSURLSessionDataTask *task, id responseObject) {
        SLResultModel *model = [SLResultModel mj_objectWithKeyValues:responseObject];
        model.rawdata = responseObject;
        completion(model);
    } failure:^(NSURLSessionDataTask *task, NSError *error, id responseObject) {
        SLResultModel *model = [SLResultModel mj_objectWithKeyValues:responseObject];
        model.rawdata = responseObject;
        model.msg = @"网络请求失败了";
        completion(model);
    }];
}



- (void)requestWithManager:(AFHTTPSessionManager *)manager
                      path:(NSString *)url
                    method:(HttpRequestType)method
               paramenters:(NSMutableDictionary *)params
                  httpBody:(NSData *)httpBody
                   success:(SuccessBlock)success
                   failure:(FailureBlock)failure {
    if (!params) {
        params = [NSMutableDictionary dictionary];
    }
    NSString *methodStr = nil;
    switch (method) {
        case HttpRequestGet:
            methodStr = @"GET";
            break;
        case HttpRequestPost:
            methodStr = @"POST";
            break;
        case HttpRequestPut:
            methodStr = @"PUT";
            break;
        case HttpRequestDelete:
            methodStr = @"DELETE";
            break;
        default:
            break;
    }
    NSError *serializationError = nil;
    NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:methodStr URLString:[[NSURL URLWithString:url relativeToURL:manager.baseURL] absoluteString] parameters:params error:&serializationError];
    
    if (httpBody) {
        
        request.HTTPBody = httpBody;
    }
    //请求头
//    if ([LoginManager shareLoginManager].isLogin) {
        [request setValue:[LoginManager shareLoginManager].userModel.token forHTTPHeaderField:@"t"];
        NSLog(@"登录token:%@",[LoginManager shareLoginManager].userModel.token);
        NSString * str =[CloudPushSDK getDeviceId];
        [request setValue:str forHTTPHeaderField:@"uuid"];
        [request setValue:str forHTTPHeaderField:@"udid"];
        NSLog(@"登录uuid:%@",[LoginManager shareLoginManager].userModel.uuid);
//    }
    if (serializationError) {
        if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
            dispatch_async(self.manager.completionQueue ?: dispatch_get_main_queue(), ^{
                failure(nil, serializationError, nil);
            });
#pragma clang diagnostic pop
        }
        return ;
    }
    //    [SWLogger logDebugInfoWithRequest:request requestParams:params httpMethod:methodStr];
    
    [self callApiWithManager:manager request:request success:success fail:failure];
    
}

- (NSNumber *)callApiWithManager:(AFHTTPSessionManager *)manager request:(NSURLRequest *)request success:(SuccessBlock)success fail:(FailureBlock)fail
{
    
    // 跑到这里的block的时候，就已经是主线程了。
    __block NSURLSessionDataTask *dataTask = nil;
    dataTask = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSNumber *requestID = @([dataTask taskIdentifier]);
        [self.dispatchTable removeObjectForKey:requestID];
        if (error) {
            
            if (fail) {
                
                fail(dataTask, error, responseObject);
            }
            
        } else {
            success(dataTask, responseObject);
        }
    }];
    NSNumber *requestId = @([dataTask taskIdentifier]);
    
    self.dispatchTable[requestId] = dataTask;
    [dataTask resume];
    
    return requestId;
}

- (NSString *)getSubUrl:(NSString *)action parameter:(NSString *)parameter
{
    return [NSString stringWithFormat:@"%@/%@", action, parameter];
}

#pragma mark - socket

- (void)user:(NSInteger)userid isValidToken:(NSString *)token completion:(ResultResponseBlock)completion {
    NSMutableDictionary *params = [@{@"userId" : @(userid),
                                     @"token" : token
    } mutableCopy];
    [self requestWithPath:@"redis/isToken" method:HttpRequestPost paramenters:params completion:completion];
}


#pragma mark -- 分页

- (void)page:(PageAction)action params:(NSDictionary *)params completion:(ResultResponseBlock)completion
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:params];
    switch (action) {
        case PageActionNone:
            [self requestWithPath:@"Index/more" method:HttpRequestGet paramenters:dict completion:completion];
            break;
    }
    
}

#pragma mark - 消息部分
// 获取服务器时间戳
- (void)currentTimestampCompleted:(ResultResponseBlock)completion {
    [self requestWithPath:@"/common/times" method:HttpRequestPost paramenters:nil completion:completion];
}

// 下载图片
- (void)downloadImageFile:(NSString *)src targetPath:(NSString *)path progress:(void (^)(NSProgress *downloadProgress))progress completion:(void (^)(NSError *error))completion {
    NSString *urlStr = [src stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:urlStr]];
    NSURLSessionDownloadTask *downloadTask = [self.manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        progress ? progress(downloadProgress) : nil;
        AAIMLog(@"正在下载图片。。。。。。");
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSURL *filePathUrl = [NSURL fileURLWithPath:path];
        return filePathUrl;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        completion ? completion(error) : nil;
        if (!error) {
            AAIMLog(@"图片下载完成。。。。。。");
        } else {
            AAIMLog(@"!!!!!!!!!!!!!!图片下载失败！！！！！！！！！！");
        }
    }];
    [downloadTask resume];
}

// 下载语音文件
- (void)downloadVoiceFile:(NSString *)src targetPath:(NSString *)path progress:(void(^)(NSProgress *downloadProgress))progress completion:(void (^)(NSError *error))completion {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",LIFT_APP_USER_VOICE_KEY,src]]];
    NSURLSessionDownloadTask *downloadTask = [self.downloadManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        progress ? progress(downloadProgress) : nil;
        AAIMLog(@"正在下载语音。。。。。。");
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSURL *filePathUrl = [NSURL fileURLWithPath:path];
        return filePathUrl;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (!error) {
            AAIMLog(@"语音下载完成");
        } else {
            AAIMLog(@"语音下载失败");
        }
        completion ? completion(error) : nil;
    }];
    [downloadTask resume];
    
}

//请求临时token
- (void)requestTempTokenWithPath:(NSString *)url method:(HttpRequestType)method completion:(SuccessBlock)completion{
    [self requestWithManager:self.manager path:url method:method paramenters:nil httpBody:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        completion(task,responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error, id responseObject) {
        //        completion(task,responseObject);
    }];
}

// 上传图片
- (void)uploadImage:(UIImage *)image withURL:(nonnull NSString *)url withToken:(nonnull NSString *)token completion:(nonnull SuccessBlock)completion {
    NSLog(@"-------------%@",token);
    NSString * uuids = [LoginManager shareLoginManager].userModel.uuid;
    if (!uuids) {
        uuids = [[UIDevice currentDevice].identifierForVendor UUIDString];
    }
    NSDictionary *params = @{@"t" : token,@"uuid":uuids};
    [self.upLoadManager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //        压缩-添加-上传图片
        
        CGFloat compression = 1;
        CGFloat maxLength = 3072;
        NSData *data = UIImageJPEGRepresentation(image, compression);
        
        if (data.length/1024 < maxLength){
            
        }else{
            CGFloat max = 1;
            CGFloat min = 0.1;
            for (int i = 0; i < 6; ++i) {
                compression = (max + min) / 2;
                data = UIImageJPEGRepresentation(image, compression);
                //                   NSLog(@"Compression = %.1f", compression);
                //                   NSLog(@"daxiao:%ld",data.length);
                if (data.length < maxLength * 0.9) {
                    min = compression;
                } else if (data.length > maxLength) {
                    max = compression;
                } else {
                    break;
                }
            }
        }

        [formData appendPartWithFileData:data name:@"file" fileName:@"touxiang.png" mimeType:@"multipart/form-data"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        SLResultModel *res = [SLResultModel mj_objectWithKeyValues:responseObject];
        NSLog(@"返回结果：%@",responseObject[@"message"]);
        completion(task, responseObject);
        //        res.rawdata = responseObject;
        //        completion(res);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"出错：%@",error);
        //        SLResultModel *res = [SLResultModel new];
        //        res.result = 0;
        //        res.info = @"上传失败哟";
        
    }];
}


// 上传图片
- (void)uploadMoreImage:(UIImage *)image withURL:(nonnull NSString *)url withToken:(nonnull NSString *)token withType:(nonnull NSString *)type completion:(nonnull SuccessBlock)completion{
    NSLog(@"-------------%@",token);
    NSDictionary *params = @{@"t" : token,@"uuid":[LoginManager shareLoginManager].userModel.uuid,@"tpye":type};
    
    [self.upLoadManager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //        压缩-添加-上传图片
            CGFloat compression = 1;
            CGFloat maxLength = 3072;
            NSData *data = UIImageJPEGRepresentation(image, compression);
            
            if (data.length/1024 > maxLength){
                CGFloat max = 1;
                CGFloat min = 0.1;
                for (int i = 0; i < 6; ++i) {
                    compression = (max + min) / 2;
                    data = UIImageJPEGRepresentation(image, compression);
                    if (data.length < maxLength * 0.9) {
                        min = compression;
                    } else if (data.length > maxLength) {
                        max = compression;
                    } else {
                        break;
                    }
                }
        }
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString  stringWithFormat:@"%@.png", dateString];
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"multipart/form-data"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        SLResultModel *res = [SLResultModel mj_objectWithKeyValues:responseObject];
        NSLog(@"上传举报图片返回结果：%@",responseObject[@"message"]);
        completion(task, responseObject);
        //        res.rawdata = responseObject;
        //        completion(res);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"举报图片出错：%@",error);
        //        SLResultModel *res = [SLResultModel new];
        //        res.result = 0;
        //        res.info = @"上传失败哟";
        
    }];
}
-(void)uploadChattingImage:(UIImage*)image completion:(ResultResponseBlock)completion
{
    NSDictionary *parmas = @{@"uuid" : [NSString stringWithFormat:@"%@",[LoginManager shareLoginManager].userModel.uuid],
    @"t"  : [NSString stringWithFormat:@"%@",[LoginManager shareLoginManager].userModel.token]
                             ,@"type":@"2"};
    [self.chatFileManager POST:@"/upload" parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传文件参数
        long long time = [ChatTool shareChatTool].currentTimestamp;
        NSString *fileName = [NSString stringWithFormat:@"%lld.png",time];
        [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:@"file" fileName:fileName mimeType:@"image/jpeg"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SLResultModel *res = [SLResultModel mj_objectWithKeyValues:responseObject];
        res.rawdata = responseObject;
        completion(res);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        SLResultModel *res = [SLResultModel new];
        res.result = 0;
        res.info = @"上传失败哟";
        completion(res);
    }];
}

// 上传语音
- (void)uploadVoiceFile:(NSString *)path completion:(ResultResponseBlock)completion {
    NSDictionary *parmas = @{@"uuid" : [NSString stringWithFormat:@"%@",[LoginManager shareLoginManager].userModel.uuid],
                             @"t"  : [NSString stringWithFormat:@"%@",[LoginManager shareLoginManager].userModel.token]
                            ,@"type":@"1" };
    [self.chatFileManager POST:@"/upload" parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传文件参数
        long long time = [ChatTool shareChatTool].currentTimestamp;
        NSString *fileName = [NSString stringWithFormat:@"%lld.wav",time];
        NSData *voiceData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]];
        [formData appendPartWithFileData:voiceData name:@"file" fileName:fileName mimeType:@"audio/x-wav"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SLResultModel *res = [SLResultModel mj_objectWithKeyValues:responseObject];
        res.rawdata = responseObject;
        completion(res);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        SLResultModel *res = [SLResultModel new];
        res.result = 0;
        res.info = @"上传失败哟";
        completion(res);
    }];
    
}

@end
